const RESOLVE = 'resolved'
const REJECT = 'rejected'
const PENDING = 'pending'
const handlePromise = (result, newPromise, resolve, reject) => {
    if (result === newPromise) {
        throw new Error('can not return oneself')
    }
    if ((typeof result === 'object ' && typeof result !== null) || typeof result === 'function')) {
        const then = result.then
        if (typeof then === 'function') {

        }
    } else {
        resolve(result)
    }
}
class JJPromise {
    status = PENDING
    result = undefined
    reason = undefined
    onResolvedArr = []
    onRejectedArr = []
    constructor(execution) {
        const resolve = (result) => {
            if (this.status === PENDING) {
                this.result = result
                this.status = RESOLVE
                this.onResolvedArr.map((fn) => fn())
            }
        }
        const reject = (reason) => {
            if (this.status === PENDING) {
                this.reason = reason
                this.status = REJECT
                this.onResolvedArr.map((fn) => fn())
            }
        }
        execution(resolve, reject)
    }
    then(onResolved, onRejected) {
        const newPromise = new JJPromise((resolved, reject) => {
            if (this.status === RESOLVE) {
                setTimeout(() => {
                    const result = onResolved(this.result)
                    handlePromise(result, newPromise, resolve, reject)
                }, 0);
            }
            if (this.status === REJECT) {
                setTimeout(() => {
                    const result = onRejected(this.reason)
                    handlePromise(result, newPromise, resolve, reject)

                }, 0);
            }
            if (this.status === PENDING) {
                this.onResolvedArr.push(() => {
                    onResolved(this.result)
                    handlePromise(result, newPromise, resolve, reject)
                })
                this.onRejectedArr.push(() => {
                    onRejected(this.result)
                    handlePromise(result, newPromise, resolve, reject)
                })
            }
        })
        return newPromise
    }
}
module.exports = JJPromise